package sockethomework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Server {
    private ServerSocket serverSocket;//总机
    private Map<String, PrintWriter> allOut = new HashMap<>();


    public Server() {
        try {
            System.out.println("正在启动服务器");
            serverSocket = new ServerSocket(8888);
            System.out.println("服务器启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户连接了");




            }
        } catch (IOException e) {
            e.printStackTrace();//可删可不删
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    /**
     * 该线程任务用于负责与指定的客户端交互
     */
    private class ClientHandler implements Runnable {

        private Socket socket;
        private String host;//记录该客户端的Ip地址
        private String nickname;//记录客户端的昵称

        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);

                nickname = br.readLine();//读取客户端送过来的昵称
                synchronized (allOut) {//向集合中添加元素时需要添加同步机制，保证多个线程不能同时添加
                    allOut.put(nickname, pw);//将客户端输出流存入共享群聊集合里
                }
                sendMessageToAll("上线了，当前在线人数：" + allOut.size());//通知所有客户端，该用户上线了


                String message;
                while ((message = br.readLine()) != null) {
                    if (message.startsWith("@")) {//如聊天内容以"@"开头则表示为私聊
                        sendMessageToSomeone(message);   //调用私聊方法实现私聊
                    } else {//否则为群聊
                        sendMessageToAll("说:" + message);//调用群聊方法实现群聊
                    }
                }
            } catch (IOException e) {
            } finally {
                synchronized (allOut) {//从集合中删除元素需要添加同步机制，保证多个线程不能同时删除
                    allOut.remove(nickname);
                }
                sendMessageToAll("下线了，当前在线人数：" + allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void sendMessageToAll(String message) {
            System.out.println(nickname + "[" + host + "]" + message);
            synchronized (allOut) {//群发时也要保证多个线程同步处理
                for (PrintWriter o : allOut.values()) {
                    o.println(nickname + "[" + host + "]" + message);
                }
            }
        }

        private void sendMessageToSomeone(String message) {
            if (message.matches("@.+:.+")) {//验证私聊格式是否符合
                String toNickName = message.substring(1, message.indexOf(":"));
                if (allOut.containsKey(toNickName)) {
                    PrintWriter pw = allOut.get(toNickName);//获取对方的输出流
                    String toMessage = message.substring(message.indexOf(":" )+1);//截取私聊内容
                    pw.println(nickname + "悄悄对你说：" + toMessage);
                } else {
                    PrintWriter pw = allOut.get(nickname);//根据昵称获取当前客户端的输出流
                    pw.println("该用户[" + toNickName + "]不在线！");
                }
            } else {//格式不正确，通知当前客户端格式不对
                PrintWriter pw = allOut.get(nickname);//根据昵称获取其对应的输出流
                pw.println("私聊格式不正确！");
            }
        }

    }


}






























